package com.cai.baselibrary.mvp.view

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment
import com.cai.baselibrary.model.EventBean
import com.cai.baselibrary.mvp.IView
import com.cai.baselibrary.mvp.presenter.IPresenter
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseFragment : Fragment(),IView {
    protected var rootView :View? = null

    /**建立集合是防止出现多个以后的处理方式会发生改变*/
    private val mAllPresenters = HashSet<IPresenter<*>>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        rootView = inflater.inflate(getLayoutView(),container)
        addPresenters()
        mAllPresenters.forEach { it.onCreateView(arguments) }
        return rootView
    }

    override fun onStart() {
        super.onStart()
        if (isRegisteredEventBus()){
            EventBus.getDefault().register(this)
        }

        mAllPresenters.forEach { it.onStart() }
    }

    override fun onResume() {
        super.onResume()
        mAllPresenters.forEach { it.onResume() }
    }

    override fun onPause() {
        super.onPause()
        mAllPresenters.forEach { it.onPause() }
    }

    override fun onStop() {
        super.onStop()

        if (isRegisteredEventBus()) {
            EventBus.getDefault().unregister(this)
        }
        mAllPresenters.forEach { it.onStop() }
    }

    override fun onDestroy() {
        super.onDestroy()
        mAllPresenters.forEach { it.onDestroy() }
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    fun <T> onMessageEvent(event: EventBean<T>) { /* Do something */
        onEventBus(event)
    }


    //--------------------------------------------------------

    protected open fun <T> onEventBus(data: EventBean<T>){

    }

    /**
     * 是否注册EventBus
     * return true返回注册监听。false取消注册
     */
    protected open fun isRegisteredEventBus():Boolean{

        return false
    }
    open fun getPresenters():MutableList<IPresenter<*>>{
        return mutableListOf(mPresenter)
    }


    /**返回布局*/
    protected abstract fun getLayoutView():Int @SuppressLint("SupportAnnotationUsage") @LayoutRes


    private fun addPresenters() {
        getPresenters().forEach { mAllPresenters.add(it)}
    }







}